#!/bin/bash

# check if we have 2 arguments
if [ "$#" -ne 2 ]; then
  echo "Usage: $0 input_source output_source" >&2
  exit 1
fi

if [ ! -f $1 ]; then
  echo "Input source $1 is not valid!" >&2
  exit 1
fi

# include paths:
# - C++AMP header
# - libc++ header
# - Bolt source header
# - Bolt header generated
# - Boost header

# tools search priority:
# 1) $HCC_HOME
# 2) @LLVM_TOOLS_DIR@ : build directory
# 3) @CMAKE_INSTALL_PREFIX@ : default install directory

if [ -n "$HCC_HOME" ] && [ -e "$HCC_HOME" ]; then
  CLANG=$HCC_HOME/bin/clang++
  CLAMP_CONFIG=$HCC_HOME/bin/clamp-config
  CLAMP_CONFIG_FLAGS="--bolt --cxxflags"
  REWRITE=$HCC_HOME/lib/libStmtRewriter.so
elif [ -d @LLVM_TOOLS_DIR@ ]; then
  CLANG=@PROJECT_BINARY_DIR@/compiler/bin/clang++
  CLAMP_CONFIG=@PROJECT_BINARY_DIR@/build/@CMAKE_BUILD_TYPE@/bin/clamp-config
  CLAMP_CONFIG_FLAGS="--bolt --build --cxxflags"
  REWRITE=@PROJECT_BINARY_DIR@/build/@CMAKE_BUILD_TYPE@/lib/libStmtRewriter.so
elif [ -e @CMAKE_INSTALL_PREFIX@ ]; then
  CLANG=@CMAKE_INSTALL_PREFIX@/bin/clang++
  CLAMP_CONFIG=@CMAKE_INSTALL_PREFIX@/bin/clamp-config
  CLAMP_CONFIG_FLAGS="--bolt --cxxflags"
  REWRITE=@CMAKE_INSTALL_PREFIX@/lib/libStmtRewriter.so
else
    echo "ERROR: Can NOT locate HCC tools! Please specify with $HCC_HOME environmental variable." >&2
    exit 1
fi

# copy input file to a temp directory
TEMP_DIR=`mktemp -d`
cp $1 $TEMP_DIR/input.cpp

# do preprocess
$CLANG \
  `$CLAMP_CONFIG $CLAMP_CONFIG_FLAGS` \
  -stdlib=libc++ \
  -Xclang -load -Xclang $REWRITE \
  -Xclang -plugin -Xclang StmtRewriter \
  -E $1

# save the output
cp $1 $2

# restore input back
cp $TEMP_DIR/input.cpp $1

# remove temp files
rm $TEMP_DIR/input.cpp
rmdir $TEMP_DIR
